//
//  SCSegmentView.m
//  BaseSwift
//
//  Created by ghwang on 2019/7/23.
//  Copyright © 2019 ghwang. All rights reserved.
//

#import "SCSegmentView.h"
#import <Masonry.h>
#import "BaseSwift-Swift.h"
#import "UIView+SDAutoLayout.h"


@interface SCSegmentView ()
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) NSArray *itemList;

@end

@implementation SCSegmentView

-(instancetype)initWithItemList:(NSArray *)itemList{
    if (self = [super init]) {
        self.itemList = itemList;
        self.backgroundColor = [UIColor clearColor];
        self.sd_cornerRadius= @(6);
        self.layer.borderWidth = 1;
        self.layer.borderColor= UIColor.cccColor.CGColor;
        [self addSubViews];
        [self setConstraints];
        
    }
    return self;
}

-(void)addSubViews{
    [self addSubview:self.segment];
}

-(void)setConstraints{

    self.segment.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
}
- (UISegmentedControl *)segment{
    if (!_segment) {
        _segment = [[UISegmentedControl alloc]initWithItems:self.itemList];
        _segment.tintColor = [UIColor btnMainColor];
        _segment.selectedSegmentIndex = 0;//选中第几个segment 一般用于初始化时选中
        [_segment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
        UIFont *font = UIFont.smallerFont;
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        [_segment setTitleTextAttributes:attributes forState:UIControlStateNormal];
        
        _segment.selectedSegmentIndex = 0;
        _segment.layer.masksToBounds = YES;
        _segment.layer.cornerRadius = 6;
        [_segment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
        
        //设置Segment的字体
        NSDictionary *dic = @{
                              //1.设置字体样式:例如黑体,和字体大小
                              NSFontAttributeName:[UIFont smallerFont],
                              //2.字体颜色
                              NSForegroundColorAttributeName:[UIColor whiteColor]
                              };
        
        [_segment setTitleTextAttributes:dic forState:UIControlStateNormal];
    }
    return _segment;
}
- (void)segmentValueChanged:(UISegmentedControl *)segment{
    self.segmentSwitchBlock?self.segmentSwitchBlock(segment.selectedSegmentIndex):nil;
}
-(long)selectedSegmentIndex{
    return self.segment.selectedSegmentIndex;
}
@end
